//
//  HttpRequestManager.m
//  AFNetWorkingTest
//
//  Created by HawkingWang on 15/12/4.
//  Copyright © 2015年 pachira. All rights reserved.
//

#import "HttpRequestManager.h"
#import <CommonCrypto/CommonDigest.h>
#import <AFNetworking.h>

@implementation HttpRequestManager

//+(void)Wechatmethod:(RequstMethod)methodName withURL:(NSString *)url parameters:(NSDictionary *)parameter success:(completedMainBlock)completedMainBlock{
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    [session GET:url parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
//    
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
//        completedMainBlock(YES,responseObject,nil);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
//        if(response.statusCode == 401){
//            NSDictionary *dic = @{@"code":[NSString stringWithFormat:@"%ld",response.statusCode]};
//            completedMainBlock(NO,dic,@"未登录");
//        }
//        NSDictionary *allHeaders = response.allHeaderFields;
//        if(allHeaders[@"x-api-message"]!=nil){
//            NSData *data = [[NSData alloc] initWithBase64Encoding:allHeaders[@"x-api-message"]];
//            NSString *str =  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            completedMainBlock(NO,str,str);
//        }else{
//            NSString *errorMsg = [NSString stringWithFormat:@"服务器请求错误%ld",[error code]];
//            completedMainBlock(NO,nil,errorMsg);
//        }
//        
//    }];
//}

+(void)method:(RequstMethod)methodName withURL:(NSString *)url parameters:(NSDictionary *)parameter success:(completedMainBlock)completedMainBlock{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
     [session.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", nil]];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *md5UUID = [userDefaults objectForKey:XXDeviceToken];
//    DLog(@"md5UUID %@",md5UUID);
    [session.requestSerializer setValue:md5UUID forHTTPHeaderField:@"TOKEN"];
//    [session.requestSerializer setValue:@"100" forHTTPHeaderField:@"x-api-page"];
//    [session.requestSerializer setValue:@"2" forHTTPHeaderField:@"x-api-size"];
    
    if(methodName == 1){
        
        [session GET:url parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSDictionary *allHeaders = response.allHeaderFields;
            completedMainBlock(YES,responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            if(response.statusCode == 401){
//                [userDefaults setBool:NO forKey:KUserDefault_isLogin];
                [userDefaults synchronize];
                NSDictionary *dic = @{@"code":[NSString stringWithFormat:@"%ld",response.statusCode]};
                completedMainBlock(NO,dic,@"未登录");
            }
            NSDictionary *allHeaders = response.allHeaderFields;
            if(allHeaders[@"x-api-message"]!=nil){
                NSData *data = [[NSData alloc] initWithBase64Encoding:allHeaders[@"x-api-message"]];
                NSString *str =  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                completedMainBlock(NO,str,str);
            }else{
                NSString *errorMsg = [NSString stringWithFormat:@"服务器请求错误%ld",[error code]];
                completedMainBlock(NO,nil,errorMsg);
            }

        }];
    }else if(methodName == 2){
        
        [session POST:url parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSDictionary *allHeaders = response.allHeaderFields;
            if(allHeaders[@"x-api-message"]!=nil){
                NSData *data = [[NSData alloc] initWithBase64Encoding:allHeaders[@"x-api-message"]];
                NSString *str =  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            }
            completedMainBlock(YES,responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSString *errorMsg = [NSString stringWithFormat:@"服务器请求错误%ld",[error code]];
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSDictionary *allHeaders = response.allHeaderFields;
            if(allHeaders[@"x-api-message"]!=nil){
                NSData *data = [[NSData alloc] initWithBase64Encoding:allHeaders[@"x-api-message"]];
                NSString *str =  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                completedMainBlock(NO,str,errorMsg);
            }else{
                completedMainBlock(NO,nil,errorMsg);
            }
        }];
        
    }else if(methodName == 3){
        [session DELETE:url parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSDictionary *allHeaders = response.allHeaderFields;
            NSData *data = [[NSData alloc] initWithBase64Encoding:allHeaders[@"x-api-message"]];
            NSString *str =  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            completedMainBlock(YES,responseObject,nil);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSDictionary *allHeaders = response.allHeaderFields;
            NSString *errorMsg = [NSString stringWithFormat:@"服务器请求错误%ld",[error code]];
            if(allHeaders[@"x-api-message"] !=nil){
                NSData *data = [[NSData alloc] initWithBase64Encoding:allHeaders[@"x-api-message"]];
                NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                completedMainBlock(NO,str,errorMsg);
            }else{
                completedMainBlock(NO,nil,errorMsg);
            }
        }];
    }else if(methodName == 4){
        [session PUT:url parameters:parameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            completedMainBlock(YES,responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSString *errorMsg = [NSString stringWithFormat:@"服务器请求错误%ld",[error code]];
            
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSDictionary *allHeaders = response.allHeaderFields;
            if(allHeaders[@"x-api-message"] !=nil){
                NSData *data = [[NSData alloc] initWithBase64Encoding:allHeaders[@"x-api-message"]];
                NSString *str =  [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                DLog(@"str%@",str);
            }
            completedMainBlock(NO,nil,errorMsg);
        }];
    }
}


+(void)upLoadFile:(NSString *)methodName parameters:(NSDictionary *)parameter success:(completedMainBlock)completedMainBlock{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:methodName];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            completedMainBlock(YES,responseObject,nil);
        } else {
            NSString *errorMsg = [NSString stringWithFormat:@"服务器请求错误%ld",[error code]];
            completedMainBlock(NO,nil,errorMsg);
        }
    }];
    [dataTask resume];
}

+(void)downloadFile:(NSString *)methodName withDir:(NSString *)dir parameters:(NSDictionary *)parameter success:(completedMainBlock)completedMainBlock{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, dir];
    NSURL *url = [NSURL URLWithString:methodName];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    [manager downloadTaskWithRequest:request
                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                                return [NSURL fileURLWithPath:fullPath];
                            }
                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                       completedMainBlock(YES,filePath,nil);
                   }];
    [task resume];
}

+(BOOL)checkNetworkStatus{
    __block BOOL isNetworkUse = YES;
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusUnknown) {
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusReachableViaWiFi){
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusReachableViaWWAN){
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusNotReachable){
            // 网络异常操作
            isNetworkUse = NO;
            DLog(@"网络异常,请检查网络是否可用！");
        }
    }];
    [reachabilityManager startMonitoring];
    return isNetworkUse;
}


@end
